package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/7/25 22:56
 */
public class LeetCode131 {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        backtrack(s, 0, new ArrayList<>(), result);
        return result;
    }
    
    private void backtrack(String s, int startIndex, List<String> path, List<List<String>> result) {
        if (startIndex >= s.length()) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (!isPalindrome(s.substring(startIndex, i + 1))) {
                continue;
            }
            path.add(s.substring(startIndex, i + 1));
            backtrack(s, i + 1, path, result);
            path.remove(path.size() - 1);
        }
    }
    
    private boolean isPalindrome(String s) {
        if (s == null || s.length() <= 1) {
            return true;
        }
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (!Objects.equals(s.charAt(left), s.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        List<List<String>> partition = new LeetCode131().partition(input);
        System.out.println(String.join(",", partition.toString()));
    }
}
